<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :show-close="false"
    :title="isAdd ? '新增运营计划' : '修改运营计划'"
    width="750"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="计划名称" prop="operateName">
        <el-input
          v-model="form.operateName"
          placeholder="请输入计划名称"
          oninput="value=value.replace(/\s+/g, '')"
          maxlength="20"
          show-word-limit
          style="width: 360px;"
        />
      </el-form-item>
      <el-form-item label="计划人群" prop="groupName">
        <div class="selectCrowd">
          <span @click="selectCrowdFn">选择人群</span>
          <div v-if="formOptions.group">
            已选人群：{{ formOptions.group }}
          </div>
          <p>每次推送人数建议小于10万，否则容易出现延时的情况</p>
        </div>
      </el-form-item>
      <el-form-item label="计划方式" prop="planMode">
        <div class="autoPlan">
          <el-radio
            v-model="form.planMode"
            label="1"
          >自动长期计划</el-radio>
          <p>
            人群中如果有满足条件的新增客户，新增的客户会自动收到营销通知。
          </p>
        </div>
        <div v-if="form.planMode === '1'" style="display: flex; margin: 0 0 20px 0;">
          <span class="autoTimeText">计划执行时间：</span>
          <el-form-item prop="date">
            <el-date-picker
              v-model="formOptions.date"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </div>
        <div>
          <el-radio
            v-model="form.planMode"
            label="2"
          >手动定时计划</el-radio>
          <p>在指定时间向计划人群发送营销通知</p>
          <el-form-item v-if="form.planMode === '2'" prop="manualTime">
            <el-radio v-model="formOptions.timeType" label="1">立即执行</el-radio>
            <el-radio v-model="formOptions.timeType" label="2">选择执行</el-radio>
            <el-date-picker
              v-model="form.manualTime"
              type="datetime"
              placeholder="选择日期时间"
              :disabled="formOptions.timeType === '1'"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item label="优惠券配置" prop="couponName">
        <div class="couponBox">
          <el-checkbox
            v-model="formOptions.couponChecked"
            @change="vildateForm('couponName')"
          >发放优惠券</el-checkbox>
          <p class="info">
            发放优惠券能有效刺激转化（优惠券将直接发放给客户，不需要领取）
          </p>
          <template v-if="form.coupons && form.coupons.length > 0">
            <el-table
              :data="form.coupons"
              border
              :header-cell-style="{
                background: '#EEF3FF',
                color: '#333333',
              }"
              tooltip-effect="dark"
              style="width: 600px"
            >
              <el-table-column
                prop="couponName"
                label="优惠券"
                align="center"
                width="220"
              />
              <el-table-column
                prop="content"
                label="优惠内容"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="stockNumber"
                label="库存"
                align="center"
                show-overflow-tooltip
              />
              <el-table-column
                prop="number"
                align="center"
                label="赠券数"
              />
            </el-table>
          </template>
          <span
            v-if="formOptions.couponChecked"
            class="selectCoupon"
            @click="selectCoupon"
          >选择优惠券</span>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="formOptions.submitLoading" @click="handleSubmit">提交</el-button>
        <el-button @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 人群选择 -->
    <GroupSelect
      ref="groupSelectRef"
      @selected="getSelectedGroup"
    />
    <!-- 优惠券选择 -->
    <CouponSelect
      ref="couponSelectRef"
      @selected="getSelectedCoupon"
    />
  </el-dialog>
</template>

<script setup>
import { reactive, ref, shallowRef } from 'vue';
import GroupSelect from './groupSelect.vue'
import CouponSelect from './couponSelect.vue';

import {
  saveOperate,
  operateUpdate,
  getOperateDetail,
} from '@/api/customer'

const emits = defineEmits('refresh');

let visible = shallowRef(false);
let form = ref({
  operateName: '',
  planMode: '1', // 计划方式 1-自动长期计划 2-手动定时计划
  shopCrowdId: '', // 店铺人群ID
  planStart: '', // 长期计划开始时间
  planEnd: '', // 长期计划结束时间
  manualTime: '', // 手动执行时间
  coupons: [], // 优惠券列表
  shopOperateId: null,
});
const formRef = ref();
const rules = {
  operateName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' },
  ],
  groupName: [
    { required: true, validator: validateGroupCheck, trigger: 'change' }
  ],
  planMode: [
    { required: true, message: '请输入计划方式', trigger: 'blur' },
  ],
  date: [
    { required: true, validator: vildateDateCheck, trigger: 'change' }
  ],
  manualTime: [
    { required: true, validator: vildateManualCheck, trigger: 'blur' },
  ],
  couponName: [
    { required: true, validator: vildateCouponCheck, trigger: 'change' },
  ],
}
function validateGroupCheck (rule, value, callback) {
  if (!formOptions.group) {
    return callback(new Error('请选择人群'))
  }
  callback()
}
function vildateDateCheck (rule, value, callback) {
  if (form.value.planMode === '1' && !formOptions.date.length) {
    return callback(new Error('请选择计划执行时间'))
  }
  callback()
}
function vildateManualCheck (rule, value, callback) {
  if (
    form.value.planMode === '2' &&
      formOptions.timeType === '2' &&
      !form.value.manualTime
  ) {
    return callback(new Error('请选择计划执行时间'))
  }
  callback()
}
function vildateCouponCheck (rule, value, callback) {
  if (!form.value.coupons || !form.value.coupons.length) {
    return callback(new Error('请选择要发放的优惠券'))
  }
  callback()
}

function vildateForm (str) {
  if (str) {
    formRef.value.validateField(str)
  }
}
let formOptions = reactive({
  timeType: '1',
  couponChecked: false,
  date: [], // 执行时间
  group: '', // 已选中的人群
  submitLoading: false,
})

const show = (id) => {
  visible.value = true
  if (id) {
    form.value.shopOperateId = id
    getOperateInfo()
  } else {
    formOptions.group = ''
    formOptions.date = []
    form.value = {
      operateName: '',
      planMode: '1', // 计划方式 1-自动长期计划 2-手动定时计划
      shopCrowdId: '', // 店铺人群ID
      planStart: '', // 长期计划开始时间
      planEnd: '', // 长期计划结束时间
      manualTime: '', // 手动执行时间
      coupons: [], // 优惠券列表
      shopOperateId: null,
    }
  }
}

function getOperateInfo () {
  getOperateDetail({
    shopOperateId: form.value.shopOperateId
  }).then(res => {
    form.value = res.data
    form.value.planMode = form.value.planMode.toString()
    formOptions.timeType = res.data.ifImplement.toString()
  })
}

/**
 * 优惠券弹窗模块
 */
const couponSelectRef = ref();
function selectCoupon () {
  let params = {
    startTime: formOptions.date[0],
    endTime: formOptions.date[1]
  }
  if (form.value.coupons) {
    params.defaultSelects = form.value.coupons
  }
  couponSelectRef.value.show(params);
}
function getSelectedCoupon (val) {
  form.value.coupons = val
  vildateForm('couponName');
}
/**
 * 人群选择弹窗模块
 */
const groupSelectRef = ref();
function selectCrowdFn () {
  groupSelectRef.value.show();
}
function getSelectedGroup (val) {
  form.value.shopCrowdId = val.id
  formOptions.group = val.name
  vildateForm('groupName');
}

function handleClose () {
  visible.value = false
}
function handleSubmit () {
  formRef.value.validate(valid => {
    if (valid) {
      formOptions.submitLoading = true
      if (form.value.planMode === '1') {
        form.value.planStart = formOptions.date[0]
        form.value.planEnd = formOptions.date[1]
      }
      const fn = form.value.shopOperateId ? operateUpdate : saveOperate
      fn(form.value).then(res => {
        if (res.code === '') {
          ElMessage.success('操作成功')
          visible.value = false
          emits('refresh')
        }
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        formOptions.submitLoading = false
      })
    }
  })
}

defineExpose({ show })
</script>

<style lang="scss" scoped>
.selectCrowd{
  span {
    color: #409eff;
    cursor: pointer;
    font-weight: 500;
  }
  p {
    height: 30px;
    line-height: 30px;
    margin: 0;
    color: #666666;
    font-size: 12px;
  }
}
.couponBox {
  .info {
    color: #666666;
    font-size: 12px;
    margin: 0;
  }
  .selectCoupon {
    cursor: pointer;
    color: #409eff;
    font-size: 14px;
    font-weight: 500;
  }
}
</style>